package com.aofeng.hybrid.service;

import android.content.Context;

import com.aofeng.hybrid.util.LogUtil;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Sql别名和sql模块文件映射
 * Created by LGY on 2016-06-29.
 */
public class SqlMapper extends DefaultHandler {

    private static Map<String, String> map;

    public static String getSql(Context context, String alias)
    {
        if(map == null)
            loadMap(context);
        if(map.containsKey(alias))
            return map.get(alias);
        else
            return null;
    }

    public static void loadMap(Context context) {
        try {
            map = new HashMap<String, String>();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(new SqlMapper());
            InputSource is = new InputSource("file://" +context.getFilesDir().getAbsolutePath() + File.separator + "sql.xml");
            reader.parse(is);
        } catch (Exception e) {
            LogUtil.d("SqlMapper", "解析sql映射出错。");
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if(localName.equals("sql"))
            map.put(attributes.getValue("alias"), attributes.getValue("path"));
    }

}
